<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class PayController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    /*
        充值卡生成
    */
    public function getAdd()
    {
        // 解析模板
        return view('admin.pay.add');
    }

    /*
        执行生成
    */
    public function postInsert(Request $request)
    {
        // 获取数据
        $data = $request->all();
        $res = DB::table('dota_pay')->orderby('id','DESC')->first();
        // dd($res);
        // 判断是否有充值卡数据
        if($res){
            // 获取充值卡账号
            $pnum = $res->number;
        }else{
            // 设定初始充值卡账号
            $pnum = '10000000';
        }
        // 循环生成

        for ($i=1; $i <=$data['cnum'] ; $i++) { 
            $pnum += 1;
            $status = 1;
            // 密码库
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            $pass = '';
            // 随机产生密码
            while(strlen($pass)<12){ 
            // 从chars中随机产生一个字符 
            $pass .= $chars[rand(0,strlen($chars)-1)]; 
            }
            /*$data['number'] = $pnum;
            $data['password'] = $pass;
            $data['time'] = time();
            $data['status'] = $status;*/
            // 生成充值卡
            $pays = DB::table('dota_pay')->insert([
                    'number' => $pnum,
                    'password' => $pass,
                    'time' => time(),
                    'status' => $status,
                    'amount' => $data['amount'],
                ]);
        }
         if($pays){
                return back()->with('success','充值卡生成成功!!');
            }else{
                return back()->with('error','充值卡生成失败!!');
            }
    }

    /*
        充值卡展示页面
    */
    public function getIndex(Request $request)
    {
        // dd($request);
        $num = $request->input('num',10);
        // 判断是否有搜索词
        if($request->input('keywords')){
             // 查询数据
            $pays = DB::table('dota_pay')->where('amount','like','%'.$request->input('keywords').'%')->orderby('time','DESC')->paginate($num);
        }else{
             // 查询数据
            $pays = DB::table('dota_pay')->orderby('time','DESC')->paginate($num);
        }
        
        $data = $pays->all();

        // 解析模板
        return view('admin.pay.index',['data'=>$data,'pays'=>$pays,'request'=>($request->all())]);
    }

    /*
        充值卡删除操作
    */
    public function postDelete(Request $request)
    {
        // 接收要删除的id
        $id = $request->input('id');
        // dd($id);

        // 执行删除
        $res = DB::table('dota_pay')->where('id',$id)->delete();

        // 判断
        if($res){
            echo 1;
        }else{
            echo 3;
        }
    }
}
